import React, { useEffect, useMemo, useState } from 'react'
import { renderMenuItem } from "@/router";
import type { MenuProps } from "antd";
import { Menu, Layout } from "antd";
import { useLocation, useNavigate } from 'react-router-dom';


const { Sider } = Layout

// - 引入侧边栏 关联的数组


type MenuItem = Required<MenuProps>['items'][number];
function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}




const IndexSider = () => {
  const [collapsed, setCollapsed] = useState<boolean>(false);
  const navigate = useNavigate()
  const { pathname } = useLocation() // 导航实现点击高亮需要的路由地址

  // console.log(pathname);


  // 让路由配置数组与侧边栏进行关联   useMemo计算钩子函数  需要重新看???!!!!
  const items: MenuItem[] = useMemo(() => {
    return renderMenuItem().map((item: any) => {
      // 声明一个变量
      // console.log(renderMenuItem()); // 数组
      // console.log(item);
      let childrenItem
      if (item.children) {
        // console.log(item.children);
        // [getItem(undefined,undefined),getItem("数字字典","/cmn/dict"))]
        childrenItem = item.children.filter((v: any) => !v.isHide).map((item: any) => {
          return getItem(item.label, item.path)
        })
      }
      return getItem(item.label, item.path, item.icon, childrenItem);
    })
  }, [])

  // 2. 解决左侧高亮刷新失效bug
  // 2.1 获取 / 下的路由
  const [keys, setKeys] = useState<string>('/' + pathname.split('/')[1])

  // console.log('/' + pathname.split('/')[1]);
  // 2.2- 将获取的path作为keys状态的值
  useEffect(() => {
    setKeys('/' + pathname.split('/')[1])
  }, [pathname])




  return (
    <Sider breakpoint={"md"} collapsible collapsed={collapsed} onCollapse={value => setCollapsed(value)}>
      <div className="logo">
        <img src={require("@/assets/img/logo.png")} alt="" />
        <span style={{ display: collapsed ? "none" : "inline-block" }}>尚医通管理系统</span>
      </div>
      <Menu
        onClick={({ key }) => { navigate(key) }}

        // defaultSelectedKeys属性实现点击高亮
        theme="dark" defaultSelectedKeys={[pathname]} mode="inline" items={items}

        // 当前展开的 SubMenu 菜单项 key 数组 
        openKeys={[keys]}
       
        
        // 2.3-SubMenu 展开/关闭的回调 (看文档)
        onOpenChange={(openKeys: string[])=>{
          console.log(openKeys);
          
          setKeys(openKeys[1]);
        }}

        />
    </Sider>
  )
}

export default IndexSider